package com.example240703;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class PeopleStatis {
    @Autowired
    private PersonReposity personReposity;

    private Integer getId(String id_seq) {
        Person tmp = personReposity.findByIdSeq(id_seq);
        if (tmp != null) {
            return tmp.getId();
        } else {
            return -1;
        }
    }

    @PostMapping("/add") // tested
    private @ResponseBody String addPerson(@RequestParam String id_seq,
            @RequestParam String name,
            @RequestParam String gender,
            @RequestParam Integer age) {
        if (personReposity.existsIdSeq(id_seq) == 1) {
            return "oops, known person.\n";
        }
        Person p = new Person();
        p.setIdSeq(id_seq);
        p.setName(name);
        p.setGender(gender);
        p.setAge(age);
        personReposity.save(p);
        return "saved\n";
    }

    @PostMapping("remove") // tested
    private @ResponseBody String removePerson(@RequestParam String id_seq) {
        Person tmp = personReposity.findByIdSeq(id_seq);
        if (tmp == null) {
            return "oops, unknown person.\n";
        } else {
            personReposity.delete(tmp);
            return "deleted person\n" + tmp;

        }
    }

    @PostMapping("/update") // tested
    private @ResponseBody String updatePerson(@RequestParam String id_seq,
            @RequestParam String name,
            @RequestParam String gender,
            @RequestParam Integer age) {

        Person p = personReposity.findByIdSeq(id_seq);

        if (p == null) {
            return "oops, unknown person.\n";
        }
        if (name != null) {
            p.setName(name);
        }
        if (gender != null) {
            p.setGender(gender);
        }
        if (age != null) {
            p.setAge(age);
        }
        personReposity.save(p);
        return "updated\n";
    }

    @PostMapping("/find") // tested
    private @ResponseBody Person postFindPerson(@RequestParam String id_seq) {
        return personReposity.findByIdSeq(id_seq);
    }

    @GetMapping("/find/{id_seq}") // tested
    private @ResponseBody Person getFindPerson(@PathVariable String id_seq) {
        System.out.println(personReposity.findByIdSeq(id_seq));
        return personReposity.findByIdSeq(id_seq);
    }

    @GetMapping("/show") // tested
    private @ResponseBody Iterable<Person> showAllPeople() {
        return personReposity.findAll();
    }
}
